<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\PayTypeRequest;
use App\Models\Config;
use App\Models\DealLine;
use App\Models\DealLog;
use App\Models\EDealLog;
use App\Models\PresentCard;
use App\Models\Recharge;
use App\Models\User;
use App\Models\UserCard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

/**
 * @title 用户会员卡
 * @description 接口说明
 * @header name:accessToken require:1 default: desc:用户token
 */

class UserCardController extends ApiController
{

    /**
     * @title 赠送卡列表
     * @description 接口说明
     * @author wjx
     * @url /api/usercard/my_member_cards
     * @method POST
     * @module 赠送卡
     *
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     * @return user_cards:卡列表@
     * @user_cards id:卡ID use_shop:可用店铺 card_num:卡号 used_by:被谁使用
     */
    public function my_member_cards(Request $request, UserCard $user_card)
    {
        $user = $request->user;
        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }
        if ($loadType == 'more') {
            $user_cards = $user_card->filters([['user_id', '=', $user->id], ['card_type', '=', 1], ['id', '<', $startId]])->with(['shop', 'user'])->take($offset)->orderBy('id', 'desc')->get();
        } else {
            $user_cards = $user_card->filters([['user_id', '=', $user->id], ['card_type', '=', 1], ['id', '>', $startId]])->with(['shop', 'user'])->take($offset)->orderBy('id', 'desc')->get();
        }
        foreach ($user_cards as $key => $value) {
            $user_cards[$key] = $value->transform_data();
        }

        return $this->success($user_cards);
    }

    public function use_member_card(Request $request, UserCard $user_card, PayTypeRequest $payRequest)
    {
        $user = $request->user;
        $card_num = $request->card_num;
        if (!$card_num) {
            return $this->failed('缺少参数card_num');
        }
        $pay_type = $request->pay_type;
        $user_card = $user_card->where('card_num', $card_num)->first();
        if (!$user_card) {
            return $this->failed('卡号不存在');
        }
        if ($user_card->is_used == 1) {
            return $this->failed('卡号已被使用');
        }
        if ($user->is_member == 1) {
            $user->member_end_time = strtotime('+1month', $user->member_end_time);
            $user->shop_id = $user_card->shop_id;
            $user->save();
            $user_card->is_used = 1;
            $user_card->used_by = $user->id;
            $user_card->save();
            return $this->message('使用成功');
        } else {
            switch ($pay_type) {
                case '1':
                    $res = $this->useCardByWallet($request);
                    if ($res !== true) {
                        return $this->failed($res['message']);
                    } else {
                        return $this->message('使用成功');
                    }
                    break;
                case '2':
                    $user_card->is_used = 1;
                    $user_card->used_by = $user->id;
                    $recharge = new Recharge();
                    $recharge->user_id = $user->id;
                    $recharge->money = 500;
                    $recharge->type = 5; //支付押金
                    $recharge->pay_type = 2; //默认微信
                    $recharge->status = 1; //待付款
                    $recharge->out_trade_no = set_order_no();

                    DB::beginTransaction();
                    try {
                        $user_card->save();
                        $recharge->save();
                        DB::commit();
                        $pay = app('wechat_pay')->app([
                            'out_trade_no' => $recharge->out_trade_no,
                            'total_fee' => 500 * 100, // 单位是分。
                            // 'total_fee' => 1, // 单位是分。
                            'body' => '衣E会员押金支付', // 订单描述
                        ]);
                        return $this->success(json_decode($pay->getContent()));
                    } catch (\Exception $exception) {
                        DB::rollBack();
                        return $this->failed('出现异常，请稍后重试');
                    }
                    break;
                case '3':
                    $res = $this->useCardByTmc($request);
                    if ($res) {
                        return $this->message('使用成功');
                    } else {
                        return $this->failed($res['message']);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public function useCardByWallet($request)
    {
        $user = $request->user;
        $wallet = $user->wallet;
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }
        if ($wallet->money < 500) {
            return ['message' => "可用余额不足"];
        }
        $user_card = UserCard::where('code', $request->code)->first();

        $user_card->is_used = 1;
        $user_card->used_by = $user->id;
        $user_card->used_at = date('Y-m-d H:i:s');

        $user->is_member = 1;
        switch ($user_card->card_level) {
            case '1':
                $user->member_end_time = strtotime('+1month');
                $user->level = 3;
                break;
            case '2':
                $user->member_end_time = strtotime('+3month');
                $user->level = 3;
                break;
            case '3':
                $user->member_end_time = strtotime('+1year');
                $user->level = 6;
                break;
            default:
                break;
        }

        $user->member_start_time = time();

        $wallet->deposit = 500;
        $wallet->money = bcsub($wallet->money, 500, 2);
        DB::beginTransaction();
        try {
            $user->save();
            $user_card->save();
            $wallet->save();
            DealLog::add_log($user->id, 0, 500, 2, '押金消耗(余额)');

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['message' => '出现异常，请稍后重试'];
        }
    }
    public function useCardByTmc($request)
    {
        $user = $request->user;
        $wallet = $user->wallet;
        $today_price = DealLine::orderBy('id', 'desc')->value('price');
        $total_e = bcdiv(500, $today_price, 8);
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }
        if ($wallet->tmc < $total_e) {
            return ['message' => "可用余额不足,需要" . $total_e . "个e格码"];
        }
        $user_card = UserCard::where('card_num', $request->card_num)->first();
        $user_card->is_used = 1;
        $user_card->used_by = $user->id;
        $recharge = new Recharge();
        $recharge->user_id = $user->id;
        $recharge->money = 500;
        $recharge->tmc = $total_e;
        $recharge->type = 5; //支付押金
        $recharge->pay_type = 1; //
        $recharge->status = 2; //待付款
        $recharge->out_trade_no = set_order_no();

        $user->is_member = 1;
        $user->level = 3;
        $user->member_start_time = time();
        $user->member_end_time = strtotime('+1month');

        $wallet->deposit = 500;
        $wallet->tmc = bcsub($wallet->tmc, $total_e, 8);
        DB::beginTransaction();
        try {
            $user->save();
            $user_card->save();
            $recharge->save();
            $wallet->save();
            EDealLog::add_log($user->id, 0, 500, 2, '押金消耗', 0);

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['message' => '出现异常，请稍后重试'];
        }
    }
    /**
     * @title 礼品卡列表
     * @description 接口说明
     * @author wjx
     * @url /api/usercard/presentCardList
     * @method POST
     * @module 礼品卡(2.0)
     * @return banner:banner图
     * @return list:卡列表@
     * @list id:卡ID name:卡名称 content:卡内容 image:封面图
     *
     */
    public function presentCardList(Request $request, Config $config)
    {
        $user = $request->user;
        $banner = $config->get_card_banner();

        $list = PresentCard::orderBy('sort')->get();
        $list->transform(function ($item) {
            return [
                'id' => $item->id,
                'name' => $item->name,
                'content' => $item->content,
                'image' => config('app.img_url') . $item->home_image,
            ];
        });
        return $this->success(compact('banner', 'list'));
    }
    /**
     * @title 礼品卡详情
     * @description 接口说明
     * @author wjx
     * @url /api/usercard/presentCardDetail
     * @method POST
     * @module 礼品卡(2.0)
     * @param name:id type:int require:1 default: other: desc:礼品卡ID
     */
    public function presentCardDetail(Request $request, Config $config)
    {
        $user = $request->user;
        $id = $request->id;
        $list = PresentCard::where('id', $id)->first();
        if (!$list) {
            return $this->failed('礼品卡不存在');
        }
        $data = [];
        $data['id'] = $id;
        $data['font_color'] = $list->font_color;
        $data['image'] = config('app.img_url') . $list->head_image;
        $data['type'] = [
            [
                'type_id' => 1,
                'name' => "“衣E”专属会员【月卡】",
                'price' => 499,
            ],
            [
                'type_id' => 2,
                'name' => "“衣E”专属会员【季卡】",
                'price' => 1300,
            ],
            [
                'type_id' => 3,
                'name' => "“衣E”专属会员【年卡】",
                'price' => 4990,
            ],
        ];
        return $this->success($data);
    }
    /**
     * @title 购买礼品卡
     * @description 接口说明
     * @author wjx
     * @url /api/usercard/buyPresentCard
     * @method POST
     * @module 礼品卡(2.0)
     * @param name:id type:int require:1 default: other: desc:礼品卡ID
     * @param name:type_id type:int require:1 default: other: desc:购买类型1:月2:季度3:年
     * @param name:pay_type type:int require:1 default:1 other: desc:支付方式(1余额2微信3e格码)
     * @param name:security type:string require: default: other: desc:支付密码
     */
    public function buyPresentCard(Request $request, PayTypeRequest $payrequest, Config $config)
    {
        $user = $request->user;
        $id = $request->id;
        $type_id = $request->type_id;
        if (!in_array($type_id, [1, 2, 3])) {
            return $this->failed('支付方式错误');
        }
        $list = PresentCard::where('id', $id)->first();
        if (!$list) {
            return $this->failed('礼品卡不存在');
        }

        switch ($type_id) {
            case '1':
                $amount = 499;
                break;
            case '2':
                $amount = 1300;
                break;
            case '3':
                $amount = 4990;
                break;
            default:
                break;
        }

        switch ($payrequest->pay_type) {
            case '1':
                $res = $this->pay_by_wallet($request, $amount);
                if ($res !== true) {
                    return $this->failed($res['message']);
                } else {
                    return $this->message('购买成功');
                }
                break;
            case '2':
                $recharge = new Recharge();
                $recharge->user_id = $user->id;
                $recharge->money = $amount;
                $recharge->type = 8; //支付礼品卡
                $recharge->pay_type = 2; //默认微信
                $recharge->status = 1; //待付款
                $recharge->present_card_id = $type_id;
                $recharge->out_trade_no = set_order_no();

                DB::beginTransaction();
                try {
                    $recharge->save();
                    DB::commit();
                    $pay = app('wechat_pay')->app([
                        'out_trade_no' => $recharge->out_trade_no,
                        // 'total_fee' => $amount * 100, // 单位是分。
                        'total_fee' => 1, // 单位是分。
                        'body' => '衣E-购买礼品卡', // 订单描述
                    ]);
                    return $this->success(json_decode($pay->getContent()));
                } catch (\Exception $exception) {
                    DB::rollBack();
                    return $this->failed('出现异常，请稍后重试');
                }
                break;
            case '3':
                $res = $this->pay_by_tmc($request, $amount);
                if ($res !== true) {
                    return $this->failed($res['message']);
                } else {
                    return $this->message('购买成功');
                }
                break;
            default:
                break;
        }
    }

    public function pay_by_wallet($request, $amount)
    {
        $user = $request->user;
        $wallet = $user->wallet;
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }
        if ($wallet->money < $amount) {
            return ['message' => "可用余额不足"];
        }
        $card = new UserCard();
        $card->user_id = $user->id;
        $card->card_id = $request->id;
        $card->card_type = 2;
        $card->card_level = $request->type_id;
        $card->code = strtoupper(str_random(20));

        $wallet->money = bcsub($wallet->money, $amount, 2);
        DB::beginTransaction();
        try {
            $card->save();
            $wallet->save();
            DealLog::add_log($user->id, 0, $amount, 2, '购买礼品卡(余额)');
            DB::commit();
            return true;
        } catch (\Exception $exception) {

            DB::rollBack();
            return ['message' => '出现异常，请稍后重试'];
        }
    }

    public function pay_by_tmc($request, $amount)
    {
        $user = $request->user;
        $wallet = $user->wallet;
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }
        $today_price = DealLine::orderBy('id', 'desc')->value('price');
        $total_e = bcdiv($amount, $today_price, 8);

        if ($wallet->tmc < $total_e) {
            return ['message' => "可用余额不足,需要" . $total_e . "个e格码"];
        }
        $card = new UserCard();
        $card->user_id = $user->id;
        $card->card_id = $request->id;
        $card->card_type = 2;
        $card->card_level = $request->type_id;
        $card->code = strtoupper(str_random(20));

        $wallet->money = bcsub($wallet->money, $amount, 2);
        DB::beginTransaction();
        try {
            $card->save();
            $wallet->save();
            EDealLog::add_log($user->id, 0, $total_e, 2, '购买礼品卡', 0);
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['message' => '出现异常，请稍后重试'];
        }
    }

    /**
     * @title 我购买的
     * @description 接口说明:is_used:0未使用1已使用
     * @author wjx
     * @url /api/usercard/myPresentList
     * @method POST
     * @module 礼品卡(2.0)
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     */
    public function myPresentList(Request $request, UserCard $userCard)
    {
        $user = $request->user;

        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }

        if ($loadType == 'more') {
            $lists = $userCard->filters([['user_id', '=', $user->id], ['card_type', '=', 2], ['id', '<', $startId]])->take($offset)->orderBy('id', 'desc')->get();
        } else {
            $lists = $userCard->filters([['user_id', '=', $user->id], ['card_type', '=', 2], ['id', '>', $startId]])->take($offset)->orderBy('id', 'desc')->get();
        }
        foreach ($lists as $key => $value) {
            $lists[$key] = $value->transform_present_data();
        }
        return $this->success($lists);

    }

    /**
     * @title 兑换按钮
     * @description 接口说明:card_type:1赠送卡2礼品卡
     * @author wjx
     * @url /api/usercard/exchangeButton
     * @method POST
     * @module 兑换功能(2.0)
     * @param name:code type:int require:1 default:10 other: desc:会员卡号
     */
    public function exchangeButton(Request $request, UserCard $user_card)
    {
        $user = $request->user;
        $code = $request->code;
        $user_card = $user_card->where('code', $code)->first();
        if (!$user_card) {
            return $this->failed('卡号不存在');
        }
        if ($user_card->is_used == 1) {
            return $this->failed('卡号已被使用');
        }
        if ($user->is_member) {
            $deposit = 0;
        } else {
            $deposit = 500;
        }
        switch ($user_card->card_level) {
            case '1':
                $amount = '499/月';
                break;
            case '2':
                $amount = '1300/季';
                break;
            case '3':
                $amount = '4990/年';
                break;
            default:
                break;
        }
        $data = [];

        $data['card_type'] = $user_card->card_type;
        $data['code'] = $code;
        $data['deposit'] = $deposit;
        $data['label'] = $amount;
        if ($user_card->presentCard) {
            $data['font_color'] = $user_card->presentCard->font_color;
            $data['image'] = config('app.img_url') . $user_card->presentCard->head_image;
        }

        $msg = [];
        if ($user_card->presentCard) {
            $msg['label'] = "恭喜获得【" . $user_card->presentCard->name . "】一张！";
            $msg['image'] = config('app.img_url') . $user_card->presentCard->home_image;
        } else {
            $msg['label'] = '恭喜获得【会员卡】一张！';
            $msg['image'] = '';
        }
        return $this->success(compact('data', 'msg'));
    }
    /**
     * @title 确认按钮
     * @description 接口说明:card_type:1赠送卡2礼品卡
     * @author wjx
     * @url /api/usercard/confirmButton
     * @method POST
     * @module 兑换功能(2.0)
     * @param name:code type:int require:1 default:10 other: desc:会员卡号
     * @param name:pay_type type:int require:0 default:1 other: desc:支付方式(1余额2微信)
     * @param name:security type:string require: default: other: desc:支付密码
     */
    public function confirmButton(Request $request, UserCard $user_card)
    {
        $user = $request->user;
        $code = $request->code;
        $pay_type = $request->pay_type;
        $user_card = $user_card->where('code', $code)->first();
        if ($user_card->user_id == $user->id) {
            return $this->failed('兑换码不能本人使用');
        }
        if (!$user_card) {
            return $this->failed('卡号不存在');
        }
        if ($user_card->is_used == 1) {
            return $this->failed('卡号已被使用');
        }

        if ($user->is_member == 1) {
            switch ($user_card->card_level) {
                case '1':
                    $user->member_end_time = strtotime('+1month', $user->member_end_time);
                    $user->level = 3;

                    break;
                case '2':
                    $user->member_end_time = strtotime('+3month', $user->member_end_time);
                    $user->level = 3;

                    break;
                case '3':
                    $user->member_end_time = strtotime('+1year', $user->member_end_time);
                    $user->level = 6;
                    break;
                default:
                    break;
            }
            $user->save();
            $user_card->is_used = 1;
            $user_card->used_by = $user->id;
            $user_card->used_at = date('Y-m-d H:i:s');
            $user_card->save();

            $data = [];
            $data['card_type'] = $user_card->card_type;
            if ($user_card->presentCard) {
                $data['label'] = "恭喜获得【" . $user_card->presentCard->name . "】一张！";
                $data['image'] = config('app.img_url') . $user_card->presentCard->home_image;
            } else {
                $data['label'] = '恭喜获得【会员卡】一张！';
                $data['image'] = '';
            }
            return $this->success($data);
        } else {
            if (!in_array($pay_type, [1, 2])) {
                return $this->failed('支付方式错误');
            }
            switch ($pay_type) {
                case '1':
                    $res = $this->useCardByWallet($request);
                    if ($res !== true) {
                        return $this->failed($res['message']);
                    } else {
                        $data = [];
                        $data['card_type'] = $user_card->card_type;
                        if (count($user_card->presentCard)) {
                            $data['label'] = "恭喜获得【" . $user_card->presentCard->name . "】一张！";
                            $data['image'] = config('app.img_url') . $user_card->presentCard->home_image;
                        } else {
                            $data['label'] = '恭喜获得【会员卡】一张！';
                            $data['image'] = '';
                        }
                        return $this->success($data);
                    }
                    break;
                case '2':
                    $recharge = new Recharge();
                    $recharge->user_id = $user->id;
                    $recharge->money = 500;
                    $recharge->type = 5; //支付押金
                    $recharge->pay_type = 2; //默认微信
                    $recharge->user_card_id = $user_card->id;
                    $recharge->status = 1; //待付款
                    $recharge->out_trade_no = set_order_no();

                    DB::beginTransaction();
                    try {
                        $recharge->save();
                        DB::commit();
                        $pay = app('wechat_pay')->app([
                            'out_trade_no' => $recharge->out_trade_no,
                            // 'total_fee' => 500 * 100, // 单位是分。
                            'total_fee' => 1, // 单位是分。
                            'body' => '衣E会员-押金支付', // 订单描述
                        ]);
                        return $this->success(json_decode($pay->getContent()));
                    } catch (\Exception $exception) {
                        DB::rollBack();
                        return $this->failed('出现异常，请稍后重试');
                    }
                    break;
                case '3':

                    break;
                default:
                    break;
            }
        }
    }

    /**
     * @title 兑换记录
     * @description 接口说明:card_type:1赠送卡2礼品卡
     * @author wjx
     * @url /api/usercard/useCardLog
     * @method POST
     * @module 兑换功能(2.0)
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     */
    public function useCardLog(Request $request, UserCard $user_card)
    {
        $user = $request->user;
        $startId = $request->ID ? $request->ID : 0;
        // $offset = $request->offset ? $request->offset : 10;
        $offset = 100;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }

        if ($loadType == 'more') {
            $lists = $user_card->filters([['used_by', '=', $user->id], ['id', '<', $startId]])->take($offset)->orderBy('used_at', 'desc')->get();
        } else {
            $lists = $user_card->filters([['used_by', '=', $user->id], ['id', '>', $startId]])->take($offset)->orderBy('used_at', 'desc')->get();
        }
        foreach ($lists as $key => $value) {
            $lists[$key] = $value->transform_use_log();
        }
        return $this->success($lists);
    }

}
